package org.rabbit.mq.springbootrabbitproducer.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhs
 * @Date: 2021/6/10 15:48
 * @Description:
 */

/**
 * 生产者配置（producer）
 * 死信队列
 *  1.声明正常的交换机和队列
 *  2.声明死信交换机和队列
 *
 * 业务队列routingKey与需要绑定死信交换机的队列的routingKey一致
 */
@Configuration
public class RabbitDLXConfiguration {

    //正常交换机和队列
    public static final String EXCHANGE_NAME = "dlx_exchange";
    public static final String QUEUE_NAME = "dlx_queue";
    //死信交换机和队列
    public static final String DEAD_EXCHANGE = "dead_exchange";
    public static final String DEAD_QUEUE = "dead_queue";
    public static final String DLX_ROUTING_KEY = "dlx.#";


    //业务交换机
    @Bean("dlxExchange")
    public Exchange createExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }

    //业务队列
    @Bean("dlxQueue")
    public Queue createQueue(){
        Map<String,Object> argument = new HashMap<>();
        //指定死信交换机
        argument.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //指定死信路由键
        argument.put("x-dead-letter-routing-key",DLX_ROUTING_KEY);
        //设置过期时间
        argument.put("x-message-ttl",10000);
        //队列最大长度
        argument.put("x-max-length",10);
        return QueueBuilder.durable(QUEUE_NAME).withArguments(argument).build();
    }

    //死信交换机
    @Bean("deadExchange")
    public Exchange createDeadExchange(){
        return ExchangeBuilder.topicExchange(DEAD_EXCHANGE).durable(true).build();
    }

    //死信队列
    @Bean("deadQueue")
    public Queue createDeadQueue(){
        return QueueBuilder.durable(DEAD_QUEUE).build();
    }

    //业务交换机与业务队列绑定
    @Bean
    public Binding bind(@Qualifier("dlxExchange") Exchange exchange,@Qualifier("dlxQueue") Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with(DLX_ROUTING_KEY).noargs();
    }

    //死信交换机与死信队列绑定
    @Bean
    public Binding deadBind(@Qualifier("deadExchange") Exchange exchange,@Qualifier("deadQueue") Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with(DLX_ROUTING_KEY).noargs();
    }

}
